const app = getApp(); // 获取全局应用实例
const wuhuUrl = app.globalData.wuhuUrl;
Page({
  data: {
    // 裁剪框的初始位置和大小
    cropLeft: 0,
    cropTop: 0,
    cropWidth: 200,
    cropHeight: 200,
    // 手指初始位置
    startX: 0,
    startY: 0,
    // 是否正在移动裁剪框
    moving: false,
    photoList: [], // 图片路径列表
    currentIndex: 0, // 当前显示的图片索引
    imageStyles: [], // 存储每张图片的旋转角度
    userId: null,
    show: false,

    description: "", //描述
    address: "", //地址
    identity: "", //身份证号
    birth: "", // 出生日期
    name: "", //姓名
    sex: "", //性别
    period: "", //有效期限
    nation: "", //民族
    jiguan: "", //机关
    cutEdgeImagePath: "", //切边图像
    avatarImagePath: "", //头像
    //----------------
    whenToMove1: "", //何时由何地迁来本址
    whenToMove2: "", //何时由何地迁来本市(县)
    militarcy: "", //兵役状况
    PlaceBirth: "", //出生地
    Marrige: "", //婚姻状况
    subtype: "", //子类型
    householder: "", //户主姓名
    householderRelationship: "", //户主或与户主关系
    StandardOfCulture: "", //文化程度
    ServicePlace: "", //服务处所
    nationPlace: "", //籍贯
    recodDate: "", //登记日期
    occuption: "", //职业
    height: "", //升高
    //----------------
    DrivingType: "", //准驾车型
    FirstApplication: "", //初次领证日期
    Licence_issuing_authority: "", //发证机关
    userful_life: "", //有限期始(至)
    record: "", //档案编号
    type: "", //类型
    note: "", //记录
  },

  onLoad: function (options) {
    const userInfo = wx.getStorageSync('userInfo');
    console.log('userid传到怕照页面：', userInfo);
    this.setData({
      userId: userInfo.userId, // 设置用户ID
    });


    // 将上一个页面的路径保存在全局变量中
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    app.globalData.prevPage = prevPage.route;
    // 从全局变量中读取图片路径列表
    const photoList = app.globalData.photoList || [];
    // 初始化旋转角度数组，默认为0
    const imageStyles = new Array(photoList.length).fill("transform: rotate(0deg);");
    this.setData({
      photoList: photoList,
      imageStyles: imageStyles,
      currentIndex: 0 // 默认显示第一张图片
    });
  },
  prevPhoto: function () {
    // 显示上一张图片
    let index = this.data.currentIndex;
    index = index - 1 < 0 ? this.data.photoList.length - 1 : index - 1;
    this.setData({
      currentIndex: index
    });
  },
  nextPhoto: function () {
    // 显示下一张图片
    let index = this.data.currentIndex;
    index = index + 1 >= this.data.photoList.length ? 0 : index + 1;
    this.setData({
      currentIndex: index
    });
  },
  // 继续添加功能
  continueAdd: function () {
    console.log("继续添加")
    wx.navigateBack();
  },
  // 删除本页功能
  deletePage() {
    let {
      photoList,
      currentIndex
    } = this.data;
    if (photoList.length === 1) {
      wx.showToast({
        title: '亲，至少需要一张图片',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    photoList.splice(currentIndex, 1); // 删除当前页图片
    if (currentIndex >= photoList.length && currentIndex > 0) {
      currentIndex--; // 如果删除了最后一页，将索引前移
    }
    this.setData({
      photoList: photoList,
      currentIndex: currentIndex
    });
  },
  // 信息提取功能
  infoGet: function () {

    const userId = this.data.userId; // 获取用户ID
    const currentPhoto = this.data.photoList[this.data.currentIndex]; // 获取当前显示图片的路径
    const that = this;
    // 将图片转换为 base64 格式
    wx.getFileSystemManager().readFile({
      filePath: currentPhoto,
      encoding: 'base64',
      success: function (res) {
        const base64ImageData = res.data; // 获取图片的 base64 数据
        // console.log(base64ImageData)
        console.log(userId)
        wx.showLoading({
          title: '加载中...',
          mask: true // 是否显示透明蒙层，防止触摸穿透，默认为 false
        });
        // 发送请求给后端
        wx.request({
          url: wuhuUrl+'/ft/textin/cert_classify',
          method: 'POST',
          data: {
            base64Data: base64ImageData,
            userId: userId
          },
          success: function (res) {
            console.log(res)
            wx.hideLoading();
            const responseData = res.data.data ? JSON.parse(res.data.data) : null;

            if (!responseData || Object.keys(responseData).length === 0) {
              wx.showToast({
                title: '亲，出错了哟！',
                icon: 'error',
                duration: 2000
              });
              that.setData({
                show: false
              });
              return;
            }
            console.log(responseData)
            // 将responseData存储到infoData中
            if (responseData.type_description === "结婚证") {
              app.globalData.responseData = responseData; // 将 responseData 保存到全局变量中
              // 原页面代码
              wx.navigateTo({
                url: '../marriage_certificate/marriage_certificate?responseData=' + encodeURIComponent(JSON.stringify(responseData))
              });
            }
            if (responseData.type_description === "户口本") {
              that.setData({
                show: true,
                description: responseData['type_description'],
                name: responseData['姓名'],
                address: responseData['住址'],
                birth: responseData['出生日期'],
                whenToMove1: responseData['何时由何地迁来本址'],
                whenToMove2: responseData['何时由何地迁来本市(县)'],
                militarcy: responseData['兵役状况'],
                PlaceBirth: responseData['出生地'],
                Marrige: responseData['婚姻状况'],
                subtype: responseData['子类型'],
                householder: responseData['户主姓名'],
                householderRelationship: responseData['户主或与户主关系'],
                StandardOfCulture: responseData['文化程度'],
                ServicePlace: responseData['服务处所'],
                nationPlace: responseData['籍贯'],
                recodDate: responseData['登记日期'],
                occuption: responseData['职业'],
                identity: responseData['身份证号码'],
                height: responseData['身高'],
              })
            }
            if (responseData.type_description.includes("身份证")) {
              that.setData({
                show: true,
                description: responseData['type_description'],
                address: responseData['住址'],
                name: responseData['姓名'],
                identity: responseData['公民身份证号'],
                birth: responseData['出生'],
                sex: responseData['性别'],
                period: responseData['有效期限'],
                nation: responseData['民族'],
                jiguan: responseData['签发机关']

              });
              const avatarImageData = responseData['头像'] || '';
              if (avatarImageData) {
                that.showImage(avatarImageData, 'avatar');
              }
              // 处理切边图像
              const cutEdgeImageData = responseData['切边图像'] || '';
              if (cutEdgeImageData) {
                that.showImage(cutEdgeImageData, 'cutEdge');
              }
            }
            if (responseData.type_description === "驾驶证") {
              that.setData({
                show: true,
                address: responseData['住址'],
                type_description:responseData['type_description'],
                DrivingType:responseData['准驾车型'],
                birth:responseData['出生日期'],
                FirstApplication:responseData['初次领证日期'],
                Licence_issuing_authority:responseData['发证机关'],
                nationPlace:responseData['国籍'],
                name:responseData['姓名'],
                sex:responseData['性别'],
                userful_life:responseData['有限期始(至)'],
                record:responseData['档案编号'],
                type:responseData['类型'],
                note:responseData['记录'],
                identity:responseData['驾驶证证号']
              })
            }
          },
          fail: function (err) {
            wx.hideLoading();
            console.log("错误信息", err)
          }
        });
      },
      fail: function (err) {
        wx.hideLoading();
        console.error('读取图片文件失败', err);
      }
    });
  },
  // 显示并保存图像（头像或切边图像）
  showImage: function (base64ImageData, type) {
    const that = this;
    const fsm = wx.getFileSystemManager();
    // 根据类型设置文件名后缀
    const suffix = type === 'avatar' ? '_avatar.jpg' : '_cutEdge.jpg';
    const fileName = `${Date.now()}${suffix}`; // 生成随机文件名
    const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`; // 构建文件路径

    fsm.writeFile({
      filePath: filePath,
      data: base64ImageData,
      encoding: 'base64',
      success: function (res) {
        console.log('保存临时文件成功', res);
        // 根据类型更新对应的数据路径
        if (type === 'avatar') {
          that.setData({
            avatarImagePath: filePath // 保存临时文件路径
          });
        } else if (type === 'cutEdge') {
          that.setData({
            cutEdgeImagePath: filePath // 保存临时文件路径
          });
        }
      },
      fail: function (err) {
        console.error('保存临时文件失败', err);
      }
    });
  },


  // 旋转功能
  rotate() {
    const {
      currentIndex,
      imageStyles
    } = this.data;
    const currentRotation = parseInt(imageStyles[currentIndex].split('(')[1].split('deg')[0]);
    const newRotation = currentRotation + 90;
    imageStyles[currentIndex] = "transform: rotate(" + newRotation + "deg);";
    this.setData({
      imageStyles: imageStyles
    });
  },
  confirm: function () {
    const {
      photoList,
      imageStyles
    } = this.data;
    const processedPhotos = photoList.map((photo, index) => ({
      path: photo,
      rotation: parseInt(imageStyles[index].split('(')[1].split('deg')[0])
    }));
    // 将图片数据传递到下一个页面
    wx.navigateTo({
      url: '/pages/scan/output/output?photos=' + JSON.stringify(processedPhotos),
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },

});